from flask import Flask, render_template, jsonify, request
from flask_cors import CORS
import json
from datetime import datetime, timedelta
import random

app = Flask(__name__)
CORS(app)

# 模拟数据
mock_foods = [
    {'id': 1, 'name': '苹果', 'category': '水果', 'price': 5.00, 'stock': 100},
    {'id': 2, 'name': '牛奶', 'category': '乳制品', 'price': 10.00, 'stock': 50},
    {'id': 3, 'name': '鸡蛋', 'category': '蛋类', 'price': 2.00, 'stock': 200},
    {'id': 4, 'name': '面包', 'category': '烘焙食品', 'price': 8.00, 'stock': 80},
    {'id': 5, 'name': '鸡肉', 'category': '肉类', 'price': 20.00, 'stock': 150},
    {'id': 6, 'name': '大米', 'category': '谷物', 'price': 30.00, 'stock': 120},
    {'id': 7, 'name': '面条', 'category': '谷物', 'price': 5.00, 'stock': 60},
    {'id': 8, 'name': '酸奶', 'category': '乳制品', 'price': 6.00, 'stock': 300},
    {'id': 9, 'name': '蔬菜', 'category': '蔬菜类', 'price': 4.00, 'stock': 100},
    {'id': 10, 'name': '鱼', 'category': '海鲜', 'price': 25.00, 'stock': 90}
]

mock_sales = [
    {'food_id': 1, 'quantity': 15, 'amount': 75.00, 'region': '北京', 'sale_date': '2024-01-15'},
    {'food_id': 2, 'quantity': 8, 'amount': 80.00, 'region': '上海', 'sale_date': '2024-01-15'},
    {'food_id': 3, 'quantity': 25, 'amount': 50.00, 'region': '广州', 'sale_date': '2024-01-15'},
    {'food_id': 4, 'quantity': 12, 'amount': 96.00, 'region': '深圳', 'sale_date': '2024-01-15'},
    {'food_id': 5, 'quantity': 20, 'amount': 400.00, 'region': '杭州', 'sale_date': '2024-01-15'},
    {'food_id': 1, 'quantity': 18, 'amount': 90.00, 'region': '成都', 'sale_date': '2024-01-16'},
    {'food_id': 2, 'quantity': 10, 'amount': 100.00, 'region': '武汉', 'sale_date': '2024-01-16'},
    {'food_id': 3, 'quantity': 30, 'amount': 60.00, 'region': '西安', 'sale_date': '2024-01-16'},
    {'food_id': 4, 'quantity': 15, 'amount': 120.00, 'region': '南京', 'sale_date': '2024-01-16'},
    {'food_id': 5, 'quantity': 22, 'amount': 550.00, 'region': '重庆', 'sale_date': '2024-01-16'},
    {'food_id': 6, 'quantity': 12, 'amount': 360.00, 'region': '北京', 'sale_date': '2024-01-17'},
    {'food_id': 7, 'quantity': 8, 'amount': 40.00, 'region': '上海', 'sale_date': '2024-01-17'},
    {'food_id': 8, 'quantity': 50, 'amount': 300.00, 'region': '广州', 'sale_date': '2024-01-17'},
    {'food_id': 9, 'quantity': 15, 'amount': 60.00, 'region': '深圳', 'sale_date': '2024-01-17'},
    {'food_id': 10, 'quantity': 18, 'amount': 450.00, 'region': '杭州', 'sale_date': '2024-01-17'},
    {'food_id': 6, 'quantity': 14, 'amount': 420.00, 'region': '成都', 'sale_date': '2024-01-18'},
    {'food_id': 7, 'quantity': 9, 'amount': 45.00, 'region': '武汉', 'sale_date': '2024-01-18'},
    {'food_id': 8, 'quantity': 60, 'amount': 360.00, 'region': '西安', 'sale_date': '2024-01-18'},
    {'food_id': 9, 'quantity': 18, 'amount': 72.00, 'region': '南京', 'sale_date': '2024-01-18'},
    {'food_id': 10, 'quantity': 20, 'amount': 500.00, 'region': '重庆', 'sale_date': '2024-01-18'}
]


@app.route('/')
def index():
    """首页路由"""
    return render_template('index.html')


@app.route('/api/login', methods=['POST'])
def login():
    """用户登录接口"""
    try:
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')

        if username == 'admin' and password == 'admin123':
            return jsonify({
                'success': True,
                'message': '登录成功',
                'user': {
                    'id': 1,
                    'username': 'admin',
                    'email': 'admin@example.com'
                }
            })
        else:
            return jsonify({
                'success': False,
                'message': '用户名或密码错误'
            }), 401

    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'登录失败: {str(e)}'
        }), 500


@app.route('/api/foods')
def get_foods():
    """获取食品列表接口"""
    try:
        return jsonify({
            'success': True,
            'data': mock_foods
        })

    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取食品列表失败: {str(e)}'
        }), 500


@app.route('/api/sales/trend')
def get_sales_trend():
    """获取销售趋势数据"""
    try:
        # 生成最近7天的销售趋势数据
        trend_data = []
        for i in range(7):
            date = (datetime.now() - timedelta(days=6 - i)).strftime('%Y-%m-%d')
            total_amount = sum(sale['amount'] for sale in mock_sales if sale['sale_date'] == date)
            order_count = len([sale for sale in mock_sales if sale['sale_date'] == date])
            trend_data.append({
                'date': date,
                'total_amount': total_amount,
                'order_count': order_count
            })

        return jsonify({
            'success': True,
            'data': trend_data
        })

    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取销售趋势失败: {str(e)}'
        }), 500


@app.route('/api/sales/category')
def get_sales_by_category():
    """获取按类别统计的销售数据"""
    try:
        category_data = {}
        for sale in mock_sales:
            food = next(f for f in mock_foods if f['id'] == sale['food_id'])
            category = food['category']
            if category not in category_data:
                category_data[category] = {'total_amount': 0, 'total_quantity': 0}
            category_data[category]['total_amount'] += sale['amount']
            category_data[category]['total_quantity'] += sale['quantity']

        result = [{'category': k, 'total_amount': v['total_amount'], 'total_quantity': v['total_quantity']}
                  for k, v in category_data.items()]
        result.sort(key=lambda x: x['total_amount'], reverse=True)

        return jsonify({
            'success': True,
            'data': result
        })

    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取类别销售数据失败: {str(e)}'
        }), 500


@app.route('/api/sales/region')
def get_sales_by_region():
    """获取按地区统计的销售数据"""
    try:
        region_data = {}
        for sale in mock_sales:
            region = sale['region']
            if region not in region_data:
                region_data[region] = {'total_amount': 0, 'order_count': 0}
            region_data[region]['total_amount'] += sale['amount']
            region_data[region]['order_count'] += 1

        result = [{'region': k, 'total_amount': v['total_amount'], 'order_count': v['order_count']}
                  for k, v in region_data.items()]
        result.sort(key=lambda x: x['total_amount'], reverse=True)

        return jsonify({
            'success': True,
            'data': result
        })

    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取地区销售数据失败: {str(e)}'
        }), 500


@app.route('/api/dashboard/stats')
def get_dashboard_stats():
    """获取仪表板统计数据"""
    try:
        total_sales = sum(sale['amount'] for sale in mock_sales)
        total_orders = len(mock_sales)
        total_foods = len(mock_foods)
        today_sales = sum(sale['amount'] for sale in mock_sales
                          if sale['sale_date'] == datetime.now().strftime('%Y-%m-%d'))

        return jsonify({
            'success': True,
            'data': {
                'total_sales': float(total_sales),
                'total_orders': total_orders,
                'total_foods': total_foods,
                'today_sales': float(today_sales)
            }
        })

    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取统计数据失败: {str(e)}'
        }), 500


@app.route('/api/foods/top')
def get_top_foods():
    """获取热销食品数据"""
    try:
        food_sales = {}
        for sale in mock_sales:
            food = next(f for f in mock_foods if f['id'] == sale['food_id'])
            if food['name'] not in food_sales:
                food_sales[food['name']] = {
                    'name': food['name'],
                    'category': food['category'],
                    'total_quantity': 0,
                    'total_amount': 0
                }
            food_sales[food['name']]['total_quantity'] += sale['quantity']
            food_sales[food['name']]['total_amount'] += sale['amount']

        result = list(food_sales.values())
        result.sort(key=lambda x: x['total_quantity'], reverse=True)
        result = result[:10]  # 取前10名

        return jsonify({
            'success': True,
            'data': result
        })

    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取热销食品失败: {str(e)}'
        }), 500


if __name__ == '__main__':
    print("=" * 60)
    print("🎉 食品安全数据可视化大屏演示系统启动中...")
    print("=" * 60)
    print("📊 这是一个演示版本，使用内存数据")
    print("🌐 访问地址: http://localhost:5000")
    print("📈 数据大屏: http://localhost:5000")
    print("=" * 60)
    print("💡 提示: 按 Ctrl+C 停止应用")
    print("=" * 60)

    app.run(debug=True, host='0.0.0.0', port=5000)
